package com.yifushidai.qrcode;

import org.apache.commons.lang.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AesCbc {

    /**
     * key算法
     */
    public static final String KEY_ALGORITHM = "AES";

    /**
     * 算法名称/加密模式/填充方式
     * DES共有四种工作模式-->>ECB：电子密码本模式、CBC：加密分组链接模式、CFB：加密反馈模式、OFB：输出反馈模式 DESede/ECB/NoPadding AES/CBC/PKCS5Padding
     */
    public static final String CIPHER_ALGORITHM = "AES/CBC/PKCS5Padding";

    /**
     * 16位aes_key
     */
//    public static final String KEY_16 = PropertiesUtil.getProperty("AES_CBC_KEY");
    public static final String KEY_16 = "0123456789ABCDEF";

    public static String encrypt(String data) {
        if(StringUtils.isNotBlank(data)){
            try {
                SecretKeySpec key = new SecretKeySpec(KEY_16.getBytes(), KEY_ALGORITHM);
                Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(KEY_16.getBytes()));
                byte[] result = cipher.doFinal(data.getBytes("utf-8"));
                return btoa(Base64Util.encode(result));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String decrypt(String encryptedData) {
        if(StringUtils.isNotBlank(encryptedData)){
            try {
                SecretKeySpec key = new SecretKeySpec(KEY_16.getBytes(), KEY_ALGORITHM);
                Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
                cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(KEY_16.getBytes()));
                byte[] decryptedData = cipher.doFinal(Base64Util.decode(atob(encryptedData)));
                return new String(decryptedData,"utf-8");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String btoa(String data) throws Exception {
        return Base64Util.encode(data.getBytes("utf-8"));
    }

    public static String atob(String encodedData) throws Exception {
        return new String(Base64Util.decode(encodedData));
    }

    public static void main(String[] args) throws Exception {
//        String data = "{\"iv\":\"iv\",\"mode\":\"CryptoJS.mode.CBC\",\"padding\":\"CryptoJS.pad.Pkcs7\"}";
        String data = "666053A1";
//        String key = "1234567812345678";
//        String iv = "1234567812345678";
//        String key = HshApiUtil.generateString(16);
//        String iv = HshApiUtil.generateString(16);
        //加密
        String encryptedData = encrypt(data);
        System.out.println(encryptedData);
        //解密
        String decryptedData = decrypt(encryptedData);

//        System.out.println("解密后：" + byteToHexString(decrypted));
        System.out.println(decryptedData);
    }

}
